<template>
  <div class="msgBizEvent">
    <!-- <div>
      <el-alert type="warning" v-if="!isSys">
        <template slot='title'>
          <div>1、消息内置参数：timePoint：时间点，refCode：单号，content：话术，不可在业务参数中使用！</div>
          <div>2、使用SQL方式时，需要配置调度任务，输出字段需固定：biz_sort(业务类别,default *)、biz_type(业务类型,default
            *)、time_point(时间点)、ref_id(冗余id，可空)、ref_code(业务单号，可空)、content(参数JSON格式)！</div>
        </template>
      </el-alert>
    </div> -->
    <el-card v-loading="loading" class="aui-card--fill">
      <div slot="header" class="clearfix">
        <el-button size="small" type="primary" @click="dataFormSubmitHandle()">{{ $t('save') }}</el-button>
        <el-button size="small" @click="closeTab()">{{ $t('close') }}</el-button>
      </div>
      <el-col :span="24">
        <el-form v-loading="loading" :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
          <el-col :span="12">
            <!-- 预警项编码 -->
            <el-form-item label="预警项编码" prop="eventCode">
              <!--文本框-->
              <el-input v-model="dataForm.eventCode" placeholder="预警项编码" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 预警项名称 -->
            <el-form-item label="预警项名称" prop="eventName">
              <!--文本框-->
              <el-input v-model="dataForm.eventName" placeholder="预警项名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 事件产生方式 10:手工埋点,20:作业调度 -->
            <el-form-item label="事件产生方式" prop="msgProducerType">
              <!--单选框-->
              <el-radio-group v-model="dataForm.msgProducerType" :disabled="isSys">
                <el-radio v-for="template in $getDictList('MSG_PRODUCER_TYPE', true)" :key="template.val" :label="template.val">{{template.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 推送类型（1循环，0立即） -->
            <el-form-item label="预警消息" prop="pushType" title="循环发送：根据定义的规则每天检测，阈值表数据业务需有删除方法；推送一次：消息发送后系统会自动删除，不需业务定义删除方法。">
              <!--文本框-->
              <el-radio-group v-model="dataForm.pushType" ref="pushType">
                <el-radio v-for="template in $getDictList('MSG_PUSH_TYPE', true)" :key="template.val" :label="template.val">{{template.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <template v-if="isJob">
            <el-col :span="24">
              <!-- JOB的配置方式：BEAN:Java Bean,SQL:SQL语句 -->
              <el-form-item label="调度方法" prop="msgJobType">
                <!--文本框-->
                <el-radio-group v-model="dataForm.msgJobType">
                  <el-radio v-for="template in $getDictList('MSG_JOB_TYPE', true)" :key="template.val" :label="template.val">{{template.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="isJobSql">
              <!-- SQL -->
              <el-form-item label="SQL" prop="msgJobSql">
                <!--文本框-->
                <el-input type="textarea" :rows="6" v-model="dataForm.msgJobSql" placeholder="SQL" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isJobBean">
              <!-- Java Bean -->
              <el-form-item label="服务类名" prop="msgJobBean" title="首字母需小写">
                <!--文本框-->
                <el-input v-model="dataForm.msgJobBean" placeholder="Java Bean" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isJobBean">
              <!-- Method -->
              <el-form-item label="方法名" prop="msgJobMethod">
                <!--文本框-->
                <el-input v-model="dataForm.msgJobMethod" placeholder="Method" clearable></el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="24">
            <!-- 备注 -->
            <el-form-item label="备注" prop="remark">
              <!--文本域-->
              <el-input type="textarea" :rows="3" v-model="dataForm.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-col>
      <!-- </el-card> -->
      <el-col :span="24" class="child" v-show="true">
        <child-list ref="childList"></child-list>
      </el-col>
      <el-col :span="24" class="child" v-show="isSys">
        <el-divider content-position="left">系统预警项</el-divider>
        <el-form v-loading="loading" :model="dataForm" :rules="dataRule" ref="dataForm2" :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
          <!-- 系统预警项 -->
          <template v-if="isSys">
            <el-col :span="12">
              <el-form-item label="默认通知人" prop="contactNames">
                <el-input v-model="dataForm.contactNames" placeholder="请选择默认通知人" @focus="show">
                  <el-button slot="append" icon="el-icon-search" @click.stop="show"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </template>
          <!-- 其他 -->
          <template v-else>
            <el-col :span="12">
              <el-form-item label="系统预警项" prop="bizBigType">
                <el-select v-model="dataForm.bizBigType" filterable placeholder="请选择通知预警项" style="width:80%" clearable>
                  <el-option v-for="item in bizBigTypeList" :key="item.eventCode" :label="item.eventName" :value="item.eventCode"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="自定义通知人" prop="contactNames">
                <el-input v-model="dataForm.contactNames" placeholder="请选择通知人" @focus="show">
                  <el-button slot="append" icon="el-icon-search" @click.stop="show"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </template>
          <uni-user-select v-if="dialogVisible" ref="userSelect" @backFun="backFun" :initDataForm="{flag:1}" :multiple="true"></uni-user-select>
        </el-form>
      </el-col>
    </el-card>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import mainContent from '@/views/main-content'
import ChildList from './msgBizEvent-rule-child'
import aes from '@/utils/aes.js'
var content = mainContent

export default {
  data () {
    return {
      selData: [],
      dialogVisible: false,
      timestamp: this.$route.params.timestamp,
      loading: false,
      activeName: '1',
      currRule: {}, // 当前选择的规则
      dataForm: {
        children: [],
        deltList: [],
        id: this.$route.params.id,
        eventCode: '',
        eventName: '',
        eventClass: '',
        isSys: false,
        msgProducerType: '20',
        msgJobType: 'SQL',
        msgJobSql: '',
        msgJobBean: '',
        msgJobMethod: '',
        pushType: '0',
        remark: '',
        bizBigType: '',
        contactNames: ''
      },
      bizBigTypeList: []
    }
  },
  computed: {
    isXunhuan () {
      return this.dataForm.pushType === '1'
    },
    isJob () {
      return this.dataForm.msgProducerType === '20'
    },
    isJobSql () {
      return this.dataForm.msgJobType === 'SQL'
    },
    isJobBean () {
      return this.dataForm.msgJobType === 'BEAN'
    },
    isSys () {
      return this.dataForm.eventClass === 'SYS'
    },
    dataRule () {
      return {
        eventCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        eventName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        msgProducerType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        pushType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        bizBigType: [
          { required: this.dataForm.contactNames !== '' && this.dataForm.eventClass !== 'SYS', message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    let params = this.$route.params
    if (params.eventClass) {
      this.dataForm.eventClass = params.eventClass
    }
    if (params.eventClass === 'SYS') {
      this.dataForm.pushType = '0'
      this.dataForm.msgProducerType = '10'
    } else {
      this.dataForm.bizBigType = 'audit'
      this.loadEventSys()
    }
    // 通过路由参数pid, 控制列表请求操作
    this.$nextTick(() => {
      this.$refs['dataForm'].resetFields()
      if (this.$route.params.id) {
        this.dataForm.id = this.$route.params.id
        this.loading = true
        this.getInfo()
      }
    })
  },
  components: {
    ChildList
  },
  methods: {
    show () {
      this.dialogVisible = true
      // 等待DOM完成更新 v-if 渲染后执行
      this.$nextTick(() => {
        // 没有username没法赋默认值
        // let defaultValues = []
        // for (const item of this.dataForm.contactDTOList) {
        //   defaultValues.push({
        //     id: item.userId,
        //     realName: item.userName
        //   })
        // }
        // this.$refs.userSelect.defaultValues = defaultValues
        this.$refs.userSelect.init()
      })
    },
    backFun (data) {
      console.log('backFun', data)
      this.dataForm.contactDTOList = []
      for (const item of data) {
        this.dataForm.contactDTOList.push({
          userId: item.id,
          userName: item.realName,
          bizBigType: this.dataForm.bizBigType // 系统预警项后端服务会重置
        })
      }
      let names = data.map(function (c) {
        return c.realName
      })
      this.dataForm.contactNames = names.join(',')
    },
    // 刷新子列表
    refreshChildList () {
      if (this.dataForm.eventCode) {
        let refChild = this.$refs.childList
        refChild.dataForm.eventCode = this.dataForm.eventCode

        refChild.defaultData.eventCode = this.dataForm.eventCode
        refChild.defaultData.title = this.dataForm.eventName
        refChild.defaultData.pushType = this.dataForm.pushType
        refChild.getDataList()
      }
    },
    // 加载系统提醒预警项
    loadEventSys () {
      this.$http.get(`/msg/msgBizEvent/listSys`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return false
        }
        this.bizBigTypeList = res.data
      }).catch(() => { })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/msg/msgBizEvent/${this.dataForm.id}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return false
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }

        if (this.dataForm.contactDTOList && this.dataForm.contactDTOList.length > 0) {
          // 转换异常通知人名称
          let names = this.dataForm.contactDTOList.map(function (c) {
            return c.userName
          })
          this.dataForm.contactNames = names.join(',')
        }
        this.refreshChildList()
      }).catch(() => { })
    },
    // 关闭 tab
    closeTab () {
      content.methods.tabRemoveHandle(this.$route.name)
      this.$emit('refreshDataList')
    },
    async submit () {
      let checkFlag = true
      // 检查主表
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          this.$message({
            message: this.$t('prompt.valid'),
            type: 'error',
            duration: 1500
          })
          checkFlag = false
        }
      })
      if (!checkFlag) {
        return
      }
      // 检查主表
      this.$refs['dataForm2'].validate((valid) => {
        if (!valid) {
          this.$message({
            message: this.$t('prompt.valid'),
            type: 'error',
            duration: 1500
          })
          checkFlag = false
        }
      })
      if (!checkFlag) {
        return
      }
      // 检查子表
      let child = this.$refs.childList
      // 立即消息
      // if (this.dataForm.pushType === '0') {
      //   let data = child.getAllData()
      //   let row = data.length > 0 ? data[0] : {}
      //   this.dataForm.children = [{
      //     ...row,
      //     title: this.dataForm.eventName,
      //     eventCode: this.dataForm.eventCode,
      //     bizSort: '*',
      //     bizType: '*',
      //     timeType: '*',
      //     num: 0,
      //     timeUnit: 'D',
      //     pushType: '0'
      //   }]
      //   this.dataForm.deltList = []
      // } else {
      if (child) {
        await child.fullValidEvent().then(res => {
          if (!res) {
            checkFlag = false
          } else {
            this.dataForm.children = child.getAllData()
            this.dataForm.deltList = child.deltList
          }
        })
      }
      if (!checkFlag) {
        return
      }
      // }
      if (this.dataForm.children.length <= 0) {
        this.$message({
          message: this.$t('prompt.children'),
          type: 'error',
          duration: 500
        })
        return false
      }

      // save
      let params = {
        ...this.dataForm,
        msgJobSql: aes.encrypt(this.dataForm.msgJobSql, this.$store.state.passwordEncKey)
      }
      this.$http[!this.dataForm.id ? 'post' : 'put']('/msg/msgBizEvent/', params).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            this.closeTab()
          }
        })
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.submit()
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.msgBizEvent {
  .el-form {
    padding-right: 20px;
  }
  .child + .child {
    margin-top: 20px;
  }
  .child {
    .el-divider--horizontal {
      margin: 10px 0 20px 0;
    }
    .child_buttons {
      margin: 10px 0;
    }
  }
  .vxe-table--body-wrapper.body--wrapper {
    overflow-x: hidden;
  }
}
</style>
